#include "eventHandlerTask.h"
#include "spi/configure_device.h"
#include "monitorTimer.h"
#include "gpio/gwGpio.h"
#include "mdio/mdio.h"

static TaskHandle_t xEventHanlerTask;

extern State xState;
/*-----------------------------------------------------------*/
void task1HandleEvent(QueueHandle_t xEventQueue, Event event){
	// gw_print( "HandleEventTask1 is processing event... %d \r\n", event.ID);

	switch(event.ID){
		case EVENT_MONITOR_TIMEOUT:
		{
			xState.cnt_timer_call = xState.cnt_timer_call + 1;

			if(monitor_204b() != 0){
				if(xState.flag_spi_configuring == 0){
					xState.cnt_spi_configure_failed ++;
					xState.flag_spi_configure_ok = 0;// configure spi again !
					xState.flag_spi_configuring = 1;
					createSpiConfigureTask(xEventQueue);
				}
			}

		 	break;
		}
		case EVENT_CONFIGURE_OK:
		{
			gw_print("EVENT_CONFIGURE_OK : Configure ok and Deleted spiConfigureTask ..... \r\n");

			xState.flag_spi_configure_ok = 1;
			xState.flag_spi_configuring = 0;
			if(xState.flag_start_timer == 0){ //阻止configure重配置，再初始化组件
				xState.flag_start_timer = 1;
				start_monitor(xEventQueue); // timer task
			}

			config_SGMII();

			break;
		}
		default:
		{
			break;
		}
	}

	if(event.pData != NULL){
		vPortFree(event.pData); // pvPortMalloc
	}
}

static void eventHandlerTask( void *pvParameters )
{
	QueueHandle_t xEventQueue = (QueueHandle_t)pvParameters;
	Event event;
	for( ;; )
	{
		/* Block to wait for data arriving on the queue. */
		xQueueReceive(xEventQueue, &event, portMAX_DELAY );

		task1HandleEvent(xEventQueue, event);
	}
}

int createEventHandlerTask(QueueHandle_t xEventQueue){
    BaseType_t xReturn = xTaskCreate( eventHandlerTask, 
	                                  (const char *) "eventHandlerTask", 
									  configMINIMAL_STACK_SIZE, 
									  xEventQueue, 
									  tskIDLE_PRIORITY + 1, /* gw_priority */
									  &xEventHanlerTask);
	if(xReturn != pdPASS){
		return -1;
	}
	return 0;
}

/*********************** cli ***************************/
